import Vue from 'vue'
import VueRouter from 'vue-router'
// 登录页面
import Login from '../views/login/login.vue'
// 主页
import Layout from '../views/layout/layout.vue'
// 子组件
import Images from '../views/images/images.vue'
import Home from '../views/home/home.vue'
import Articles from '../views/articles/articles.vue'

Vue.use(VueRouter)
// 路由
const router = new VueRouter({
  routes: [{
    path: '/login',
    component: Login
  }, {
    path: '/',
    component: Layout,
    children: [
      { path: '', component: Home },
      { path: '/articles', component: Articles },
      { path: '/images', component: Images }
    ]
  }
  ]
})
// 路由守卫
const vipPages = ['/', '/articles', '/images', '']
router.beforeEach((to, from, next) => {
  const tokenStr = localStorage.getItem('tokenStr')
  // includes查找数组中是否有这个数,返回布尔值
  if (vipPages.includes(to.path) && !tokenStr) {
    next('/login')
  } else if (to.path === '/login' && tokenStr) {
    next('/')
  } else {
    next()
  }
})
export default router
